package com.gnerv.pabu.sso.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class JwtUtils {

    private static final String SECRET = "token";
    private static final Algorithm ALGORITHM = Algorithm.HMAC256(SECRET);
    private static final Long EXPIRE_TIME = 6000L;
    private static final String ISSUER = "gnerv";
    private static Map<String, Object> HEADER_PARAMS = new HashMap<>();

    static {
        HEADER_PARAMS.put("alg", "HS256");
        HEADER_PARAMS.put("typ", "JWT");
    }

    private JwtUtils() {
    }

    public static String create(Map<String, String> data) {
        Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        String token = "";
        try {
            JWTCreator.Builder builder = JWT.create();
            data.forEach((k, v) -> builder.withClaim(k, v));
            token = builder
                    .withHeader(HEADER_PARAMS)
                    .withExpiresAt(date)
                    .withIssuer(ISSUER)
                    .sign(ALGORITHM);
            return token;
        } catch (JWTCreationException exception) {
            log.info("token生成失败");
        }
        return token;
    }

    public static boolean verify(String token) {
        try {
            JWTVerifier verifier = JWT.require(ALGORITHM)
                    .withIssuer(ISSUER)
                    .build();
            DecodedJWT jwt = verifier.verify(token);
            if (ObjectUtils.isEmpty(jwt)) {
                return false;
            }
            return true;
        } catch (JWTVerificationException exception) {
            return false;
        }
    }

    public static Map claims(String token) {
        try {
            JWTVerifier verifier = JWT.require(ALGORITHM)
                    .withIssuer(ISSUER)
                    .build();
            DecodedJWT jwt = verifier.verify(token);
            Map<String, Claim> claims = jwt.getClaims();
            return claims;
        } catch (JWTVerificationException exception) {
            return null;
        }
    }

    public static String claims(String token, String key) {
        try {
            JWTVerifier verifier = JWT.require(ALGORITHM)
                    .withIssuer(ISSUER)
                    .build();
            DecodedJWT jwt = verifier.verify(token);
            return jwt.getClaim(key).toString();
        } catch (JWTVerificationException exception) {
            return "";
        }
    }

}
